var db;

var room = {
	join : function() {
		var location = document.location.toString().replace('http://', 'ws://')
				.replace('https://', 'wss://');
		if (location.substr(-1, 1) != '/') {
			location = location + "/";
		}
		location = location + "pokerservlet";
		this.ws = new WebSocket(location);
		this.ws.onopen = this.onopen;
		this.ws.onmessage = this.onmessage;
		this.ws.onclose = this.onclose;
	},

	onopen : function() {
		room.send('lamp');
	},

	send : function(message) {
		if (this.ws)
			this.ws.send(message);
	},

	chat : function(text) {
		if (text != null && text.length > 0)
			room.send(text);
	},

	onmessage : function(m) {
		if (m.data) {
			var c = m.data.indexOf(':');
			var name = m.data.substring(0, c).replace('<', '&lt;').replace('>',
					'&gt;');
			var text = m.data.substring(c + 1).replace('<', '&lt;').replace(
					'>', '&gt;');
			addMessage(text, name);
		}
	},

	onclose : function(m) {
		this.ws = null;
	}
};

function addMessage(message, name) {
	var $textarea = $('#messages');
	var text;
	if (name.length > 0) {
		text = $textarea.val() + name + ": " + message + "\n";
	} else {
		text = $textarea.val() + message + "\n";
	}
	$textarea.val(text);
	$textarea.attr({
		scrollTop : $textarea.attr('scrollHeight')
	});
	// saveToLocalStorage(message);
	saveToChatDB(message);
}

// localstorage
function saveToLocalStorage(message) {
	var key = localStorage.length;
	if (message != null) {
		try {
			localStorage.removeItem(key);
			localStorage.setItem(key, message);
		} catch (err) {
			if ((err.name).toUpperCase() == 'QUOTA_EXCEEDED_ERR') {
				localStorage.clear();
				localStorage.setItem(0, message);
			}
		}
	}
}
function getFromLocalStorage() {
	var data = "";
	for(i=0;i<localStorage.length;i++) {
		if(localStorage.getItem(i)!=null) {
			data=data+"\n"+localStorage.getItem(i);
		}
	}
	if (data != null) {
		return data;
	} else {
		return "";
	}
}

function initChatDB(){
	try {  
        if (!window.openDatabase) {  
            alert('Databases are not supported in this browser.');  
        } else {  
            var shortName = 'chatdb';  
            var version = '1.0';  
            var displayName = 'Chat Database';  
            var maxSize = 100000; // bytes
            db = openDatabase(shortName, version, displayName, maxSize);  
            createTable();  
            // selectAll();
        }  
    } catch(e) {  
  
        if (e == 2) {  
            // Version number mismatch.
            console.log("Invalid database version.");  
        } else {  
            console.log("Unknown error "+e+".");  
        }  
        return;  
    }  
}
function createTable(){  
	db.transaction(function (tx) {
		tx.executeSql('CREATE TABLE chat (id INTEGER PRIMARY KEY AUTOINCREMENT, msg)');
	});   
}  

function saveToChatDB(message) {
	db.transaction(function (tx) {
		tx.executeSql('INSERT INTO chat (msg) VALUES (?)', [message]);
	});
}
function getAllFromDB(){ 
	db.transaction(  
	        function (transaction) {  
	            transaction.executeSql("SELECT * FROM chat;", [],  
	                dataSelectHandler);  
	        } 
    );   
	
	/*
	 * tx.executeSql('SELECT * FROM chat;', function (tx, results) { var len =
	 * results.rows.length, i; for (i = 0; i < len; i++) {
	 * alert(results.rows.item(i).msg);
	 * //addMessage(results.rows.item(i).msg,""); } });
	 */
}  
function dataSelectHandler(transaction, results) {
	var output = "";
	var len = results.rows.length, i; 
	for (i = 0; i < len; i++) {
		output = output + "\n" + (results.rows.item(i).msg);
	}
	var $textarea = $('#messages');
	var text = output;
	$textarea.val(text);
	$textarea.attr({
		scrollTop : $textarea.attr('scrollHeight')
	});
}